package com.zxl.yjb.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.umeng.analytics.AnalyticsConfig;
import com.zxl.yjb.R;
import com.zxl.yjb.activity.my.FillInfoActivity;
import com.zxl.yjb.app.Const;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.LoginBean;
import com.zxl.yjb.bean.LoginSucessBean;
import com.zxl.yjb.http.HostUrl;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.CheckMobileUtils;
import com.zxl.yjb.utils.DisplayUtil;
import com.zxl.yjb.utils.SPUtil;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.widget.ClearEditText;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_phone_num)
    ClearEditText etPhoneNum;
    @BindView(R.id.et_msg_code)
    ClearEditText etMsgCode;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.tv_verify_phone_login)
    TextView tvLogin;
    @BindView(R.id.iv_protocol)
    ImageView ivProtocol;
    @BindView(R.id.tv_protocol_intent)
    TextView tvProtocol;
    @BindView(R.id.ll_user_protocol)
    LinearLayout llUserProtocol;


    private boolean isAgreeProtocol = true;
    private String phone;
    private String verifycode;
    private DataManager dataManager;
    private Disposable mDisposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void initView() {

        etPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence)) {
                    String phoneNum = charSequence.toString();
                    if (CheckMobileUtils.isMobile(phoneNum)) {//手机号正确
                        tvGetCode.setTextColor(getResources().getColor(R.color.red_color));
                        tvGetCode.setClickable(true);
                        if (!TextUtils.isEmpty(etMsgCode.getText().toString())) {
                            tvLogin.setBackgroundResource(R.drawable.login_btn_cansel_shape);
                            tvLogin.setClickable(true);
                        }
                    } else {
                        tvGetCode.setTextColor(getResources().getColor(R.color.login_tv_def_color));
                        tvGetCode.setClickable(false);
                        tvLogin.setBackgroundResource(R.drawable.login_btn_def_shape);
                        tvLogin.setClickable(false);
                    }
                } else {
                    tvGetCode.setTextColor(getResources().getColor(R.color.login_tv_def_color));
                    tvGetCode.setClickable(false);
                    tvLogin.setBackgroundResource(R.drawable.login_btn_def_shape);
                    tvLogin.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etMsgCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 3 && CheckMobileUtils.isMobile(etPhoneNum.getText().toString())) {
                    tvLogin.setBackgroundResource(R.drawable.login_btn_cansel_shape);
                    tvLogin.setClickable(true);
                } else {
                    tvLogin.setBackgroundResource(R.drawable.login_btn_def_shape);
                    tvLogin.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        //打开协议文件；
        tvProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, ProtocolActivity.class);
                startActivity(intent);
            }
        });
    }


    @OnClick({R.id.tv_get_code, R.id.tv_verify_phone_login, R.id.iv_wx_login, R.id.iv_qq_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_code:
                getCode();
                break;
            case R.id.tv_verify_phone_login:
                login();
                break;

            case R.id.ll_user_protocol://用户协议
                /*if (!isAgreeProtocol) {
                    ivProtocol.setImageResource(R.mipmap.login_f_pressed);
                    isAgreeProtocol = true;
                } else {
                    ivProtocol.setImageResource(R.mipmap.login_f_normal);
                    isAgreeProtocol = false;
                }*/
                break;

            case R.id.iv_wx_login:

                break;
            case R.id.iv_qq_login:
                break;
        }
    }

    @OnClick({R.id.tv_protocol_intent, R.id.ll_user_protocol})
    public void onViewClicked2(View view) {
        switch (view.getId()) {
            case R.id.tv_protocol_intent:
                Intent intent = new Intent(LoginActivity.this, ProtocolActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_user_protocol:
                if (!isAgreeProtocol) {
                ivProtocol.setImageResource(R.mipmap.login_f_pressed);
                isAgreeProtocol = true;
            } else {
                ivProtocol.setImageResource(R.mipmap.login_f_normal);
                isAgreeProtocol = false;
            }
                break;
        }
    }



    private void getCode() {
        phone = etPhoneNum.getText().toString();

        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        tvGetCode.setClickable(false);
        dataManager = new DataManager();
        ObserverOnNextListener observerOnNextListener = new ObserverOnNextListener<String>() {
            @Override
            public void onNext(String s) {
//                etMsgCode.setText(s);
                countDown(60);
            }
        };
        dataManager.getCode(new ProgressObserver<String>(observerOnNextListener, this), map);
    }


    private void login() {
        if (!isAgreeProtocol) {
            DisplayUtil.displayShortToast(this, "请同意用户协议!");//同意用户协议
            return;
        }
        phone = etPhoneNum.getText().toString();
        verifycode = etMsgCode.getText().toString();
        if (TextUtils.isEmpty(phone)) {//手机号为空
            DisplayUtil.displayShortToast(this, "请输入手机号!");
            return;
        }
        SPUtil.put(this, "token", "");

        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", verifycode);
        map.put("fromid", AnalyticsConfig.getChannel(this));
        map.put("ios0andr1", "1");
        dataManager = new DataManager();
        ObserverOnNextListener observerOnNextListener = new ObserverOnNextListener<LoginBean>() {
            @Override
            public void onNext(LoginBean loginBean) {
                //保存用户信息
                SaveBeanUtil.putBean(LoginActivity.this, Const.VIPINFO, loginBean.getUser());
                //登陆im
                loginIm(loginBean.getUser().getRytoken());
                if (loginBean.getUser().getFillMyInfo().equals("1"))
                {
                    SaveBeanUtil.putBean(getApplicationContext(), Const.FILLMYINFO, "1");
                    startActivity(new Intent(LoginActivity.this, FillInfoActivity.class));
                }
                else
                {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    if (TextUtils.isEmpty(loginBean.getUser().getIdcard_state()) || loginBean.getUser().getIdcard_state().equals("0")) {
                        intent.putExtra("idstatus", "0");
                    }
                    startActivity(intent);
                }

                finish();
            }
        };
        dataManager.isReg(new ProgressObserver<LoginBean>(observerOnNextListener, this), map);
    }

    private void loginIm(String ryToken) {
        try {
//            SealAppContext instance = SealAppContext.getInstance();
//            RongIMClient.ConnectCallback connectCallback = instance.getConnectCallback();
            RongIMClient.ConnectCallback connectCallback = new RongIMClient.ConnectCallback() {
                @Override
                public void onSuccess(String s) {
                    SharedPreferences sp = getSharedPreferences(Const.SHAREDPREFERENCES_FILE_NAME, Context.MODE_PRIVATE);
                    sp.edit().putString(Const.SEALTALK_LOGIN_ID, s).commit();
                    //设置当前用户的头像和昵称
                    Object bean = SaveBeanUtil.getBean(getApplication(), Const.VIPINFO);
                    if (bean != null) {
                        LoginSucessBean loginSucessBean = (LoginSucessBean) bean;
                        RongIM.getInstance().setCurrentUserInfo(new UserInfo(s,
                                loginSucessBean.getNickname(),
                                Uri.parse(HostUrl.HOSTPIC + loginSucessBean.getFace_img())));
                    }
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }

                @Override
                public void onTokenIncorrect() {
                    System.out.println("Token不正确");
                }
            };
            RongIM.connect(ryToken, connectCallback);
            //如果登陆失败重新请求token
        } catch (Exception e) {
            finish();
        }
    }

    /**
     * 倒计时
     *
     * @param count
     */
    public void countDown(final long count) {

        // 倒计时 10s
        mDisposable = Flowable.intervalRange(0, count, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        tvGetCode.setText(String.valueOf(count - aLong) + "秒");
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        tvGetCode.setText(R.string.get_code);
                        tvGetCode.setClickable(true);
                        //结束
                    }
                })
                .subscribe();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }


}
